<template>
  <div class="app-container">

    <ul class="inline-list">
      <li :class="{ 'active': activeTab === 0 }">
        <a @click="listHandle(0)">
          全部({{ count.all }})
        </a>
      </li>
      <li :class="{ 'active': activeTab === 1 }">
        <a @click="listHandle(1)">
          已发布({{ count.published }})
        </a>
      </li>
      <li :class="{ 'active': activeTab === 2 }">
        <a @click="listHandle(2)">
          草稿箱({{ count.draft }})
        </a>
      </li>
      <li :class="{ 'active': activeTab === 3 }">
        <a @click="listHandle(3)">
          回收站({{ count.recycle }})
        </a>
      </li>
      <li style="float:right;"> <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar></li>
    </ul>
     
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" >

      <el-form-item style="margin-right: 10px;">
        <!-- 下拉框 -->
         <el-select 
          v-model="queryParams.year" 
          placeholder="年" 
          style="width:80px;"
          clearable
          >
            <el-option
              v-for="item in yearList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
      </el-form-item>
      <el-form-item >
        <!-- 下拉框 -->
         <el-select 
          v-model="queryParams.month" 
          placeholder="月" 
          style="width:80px;"
          clearable
          >
            <el-option
              v-for="item in monthList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
      </el-form-item>
      
      <el-form-item prop="categoryId">
        <!-- 下拉框 -->
         <el-select 
         v-model="queryParams.categoryId" 
         placeholder="分类专栏" 
         style="width:120px;"
         clearable
         >
          <el-option
            v-for="item in blogCategoriesList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item  prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入关键词"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>

      <el-form-item style="margin-right: 10px;">
        <el-button type="primary" class="button-item"  @click="addhandle">发布文章</el-button>
      </el-form-item>

       
    </el-form>

     <el-row 
       :gutter="25" 
       class="list-item" 
       v-for="item in blog_articlesList" 
       :key="item.id">
      
      <el-col  :xs="8" :sm="4" :md="4" :lg="4" :xl="4" class="list-item-left" align="center"> 
        <el-image
              style="width: 160px; height: 90px"
              :src="item.coverImage"
              fit="cover"
            />
      </el-col>
      <el-col :xs="8" :sm="10" :md="15" :lg="20" :xl="20" class="list-item-right">
        <!-- 标题和日期 -->
        <el-row>
          <el-col :span="20"> 
            <a @click="editDataHandle(item)" >{{ item.title }}</a>&nbsp;
            
          </el-col>
          <el-col :span="4" class="item-font"> 
            {{ item.publishedTime }}
          </el-col>
        </el-row>
        <el-row class="middle-row">
          <el-col :span="24" > 
            <div v-for="category in blogCategoriesList" :key="category.id" >
              <el-tag v-if="category.id === item.categoryId" type="danger" >{{ category.name }}</el-tag>
            </div>
            
          </el-col>
        </el-row>
      <!--  点赞、评论，以及阅读次数 -->
        <el-row class="bottom-row">
          <el-col :span="19" class="item-font"> 
            阅读 {{item.views}} · 评论 666 · 点赞 {{ item.likes }}
            <span class="item-font">编号: {{ item.id }}</span>
          </el-col>
          <el-col :span="5" > 
            <a class="list-item-right-btn" @click="browseDataHandle(item)">
              <span>查看数据</span>
            </a>
            <a class="list-item-right-btn" @click="editDataHandle(item)">
              <span>编辑</span>   
            </a>
            <a class="list-item-right-btn">
              <span>浏览</span>
            </a>
            <a class="list-item-right-btn" @click="handleDelete(item)">
              <span>删除</span>
            </a>
          </el-col>
        </el-row>
      </el-col>

      <!-- elementplus分割线 -->
      <el-divider />

     </el-row>


    <AnalysisData ref="drawerRef"  :id="id"/>
     

    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script setup name="Blog_articles">
import { listBlog_articles, getBlogArticles, delBlogArticles, addBlogArticles, updateBlogArticles } from "@/api/blog/blog_articles";
import { listBlogCategories } from "@/api/blog/blog_categories";
import {loadAllParams} from "@/api/params"
import { ref } from "vue";
import AnalysisData from './components/analysis-data.vue'


const { proxy } = getCurrentInstance();

const drawerRef = ref()

const blog_articlesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const count = ref({});
const activeTab = ref(0); // 引入 activeTab 变量



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    status: null,
    userId: null,
    categoryId: null,
    year: null,
    month:null,
    params: {
      range: 0 // 初始化为 0，对应“全部”
    }
  },
  rules: {
    title: [
      { required: true, message: "文章标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "文章内容不能为空", trigger: "blur" }
    ],
   
  }
});

const { queryParams, form, rules } = toRefs(data);
const blogCategoriesList = ref([]);
const yearList = ref([])
const monthList = ref([])


/**发布文章 */
function addhandle() {
  proxy.$router.push({
    name: "EditBlogArticle"
  });
}

/** 编辑文章 */
function editDataHandle(row) {
    // 路由跳转，携带 id
  proxy.$router.push({
    name: "EditBlogArticle",
    query: { id: row.id }
  });


}

/** 初始化文章管理列表 */
function listHandle(param){
  activeTab.value = param
  getList()
}

const id = ref(0);
/** 查看数据按钮操作 */
function browseDataHandle(data) {

  id.value = data.id

  drawerRef.value.showDataDrawer()
  
}





/** 查询文章管理列表 */
function getList(item) {
  loading.value = true;
  queryParams.value.params.range = activeTab.value;

  listBlog_articles(queryParams.value).then(response => {
    blog_articlesList.value = response.rows;
    //从账号创建时间到今年，获取年份列表
    yearList.value = Array.from(
      {length: new Date().getFullYear() - 2019 + 1 }, 
      (v, k) => new Date().getFullYear() - k);
    total.value = response.total;
    
    if(item === 0)
       count.value = response.count;
    loading.value = false;
  });

  // 获取所有分类信息
  listBlogCategories(loadAllParams).then(response => {
    blogCategoriesList.value = response.rows;
  });


}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    summary: null,
    status: null,
    coverImage: null,
    userId: null,
    categoryId: null,
    year: null,
    month:null,
    views: null,
    likes: null,
    publishedTime: null,
    createTime: null,
    updateTime: null,
    params: ref({
      range: 0 // 初始化为 0，对应“全部”
    })
  };
  proxy.resetForm("blog_articlesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    year: null, // 确保 year 被重置为 null
    month: null ,// 确保 month 被重置为 null
    params: {
      range: 0 // 初始化为 0，对应“全部”
    }
  };
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文章管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBlogArticles(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文章管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["blog_articlesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBlogArticles(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBlogArticles(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除文章管理编号为"' + _ids + '"的文章？').then(function() {
    return delBlogArticles(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('blog/blog_articles/export', {
    ...queryParams.value
  }, `blog_articles_${new Date().getTime()}.xlsx`)
}

// 监听 year 的变化  question 1
watch(() => queryParams.value.year, (newYear) => {
  if (newYear !== null) {
    // 重置 month 或执行其他逻辑
    monthList.value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  } else {
    monthList.value = [];
  }
});

//统计文章数据仅赋值一次

const route = useRoute();
onMounted(() => {
  if (route.query.id !== null) {
    
    // 处理从 article_comments 页面跳转过来的情况
    queryParams.value.id = route.query.id;
  }
  getList(0);
  //query.id设置为空
  queryParams.value.id = null;
});
</script>

<style scoped lang="scss">

.el-drawer__body{
  padding:0 !important;
}

.inline-list {
  list-style-type: none; /* 去除默认的项目符号 */
  padding: 0; /* 去除默认的内边距 */
  margin: 0; /* 去除默认的外边距 */
  margin-bottom: 15px;
  font-size: 14px;
  color:grey;
}

.inline-list li {
  display: inline-block; /* 使列表项一行显示 */
  width:90px;
  text-align: center;
}
.inline-list li:hover {
 color:black;
}

.inline-list li.active {
  color: black; /* 选中状态的字体颜色 */
}


.item-font{
  font-size: 14px; 
  color:grey;
}

.list-item-left{
 
  width: 160px;
  height: 90px;
  border-radius: 2px;
  background-size: 100% 100%;
}
.list-item-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 确保子元素在垂直方向上分布 */
}

.middle-row{
  padding-top: 15px;
}

.bottom-row {
  margin-top: auto; /* 将底部行推到父元素的底部 */
  font-size:14px;
  letter-spacing: 1px;
}

.list-item-right-btn{
  margin-right:10px;
}
.list-item-right-btn:hover{
  color:gray;
}







</style>
